<template>
  <ContentWrap>
    <!-- Tab 切换 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabChange" class="mb-4">
      <el-tab-pane label="发送的汇报" name="sent">
        <!-- 发送的汇报内容 -->
        <div>
          <!-- 搜索工作栏 -->
          <el-form
            class="-mb-15px"
            :model="sentQueryParams"
            ref="sentQueryFormRef"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="汇报类型" prop="reportType">
              <el-select
                v-model="sentQueryParams.reportType"
                placeholder="请选择汇报类型"
                clearable
                class="!w-240px"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.OA_REPORT_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="接收人" prop="recipient">
              <UserSelect
                class="!w-240px"
                v-model="sentQueryParams.recipient"
                @node-change="handleUserSelect"
              />
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="sentQueryParams.createTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                class="!w-220px"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="handleSentQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
              <el-button @click="resetSentQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
              <el-button
                type="primary"
                plain
                @click="openForm('create')"
                v-hasPermi="['oa:work-report:create']"
              >
                <Icon icon="ep:plus" class="mr-5px" /> 新增
              </el-button>

            </el-form-item>
          </el-form>

          <!-- 发送的汇报列表 -->
          <el-table v-loading="sentLoading" :data="sentList" :stripe="true" :show-overflow-tooltip="true">
            <el-table-column label="汇报类型" align="center" prop="reportType">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.OA_REPORT_STATUS" :value="scope.row.reportType" />
              </template>
            </el-table-column>

            <el-table-column label="发送状态" align="center" prop="reportStatus">
              <template #default="scope">
                <el-tag type="success" v-if="scope.row.reportStatus === 1">已发送</el-tag>
                <el-tag type="danger" v-else>未发送</el-tag>
              </template>

            </el-table-column>


            <el-table-column label="接收人" align="center">
              <template #default="scope">
                <user-label :user-id="scope.row.recipient" />
              </template>
            </el-table-column>

            <el-table-column label="汇报周期" align="center" prop="reportPeriod" />
            <el-table-column
              label="汇报时间"
              align="center"
              prop="createTime"
              :formatter="dateFormatter"
              width="180px"
            />
            <el-table-column label="工作内容" align="center" prop="currentWork" />
            <el-table-column label="操作" align="center" min-width="120px">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="openForm('update', scope.row.id)"
                  v-hasPermi="['oa:work-report:update']"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="danger"
                  @click="handleSentDelete(scope.row.id)"
                  v-hasPermi="['oa:work-report:delete']"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            :total="sentTotal"
            v-model:page="sentQueryParams.pageNo"
            v-model:limit="sentQueryParams.pageSize"
            @pagination="getSentList"
          />
        </div>
      </el-tab-pane>

      <el-tab-pane label="接收的汇报" name="received">
        <!-- 接收的汇报内容 -->
        <div>
          <!-- 搜索工作栏 -->
          <el-form
            class="-mb-15px"
            :model="receivedQueryParams"
            ref="receivedQueryFormRef"
            :inline="true"
            label-width="68px"
          >
            <el-form-item label="汇报类型" prop="reportType">
              <el-select
                v-model="receivedQueryParams.reportType"
                placeholder="请选择汇报类型"
                clearable
                class="!w-240px"
              >
                <el-option
                  v-for="dict in getStrDictOptions(DICT_TYPE.OA_REPORT_STATUS)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>


            <el-form-item label="汇报人" prop="creator">
              <UserSelect
                class="!w-240px"
                v-model="receivedQueryParams.creator"
                @node-change="handleUserSelect"
              />
            </el-form-item>
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="receivedQueryParams.createTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                class="!w-220px"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="handleReceivedQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
              <el-button @click="resetReceivedQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 接收的汇报列表 -->
          <el-table v-loading="receivedLoading" :data="receivedList" :stripe="true" :show-overflow-tooltip="true">
            <el-table-column label="汇报类型" align="center" prop="reportType">
              <template #default="scope">
                <dict-tag :type="DICT_TYPE.OA_REPORT_STATUS" :value="scope.row.reportType" />
              </template>
            </el-table-column>

            <el-table-column label="汇报人" align="center">
              <template #default="scope">
                <user-label :user-id="scope.row.creator" />
              </template>
            </el-table-column>
            <el-table-column label="工作内容" align="center" prop="currentWork" />
            <el-table-column label="汇报周期" align="center" prop="reportPeriod" />
            <el-table-column
              label="汇报时间"
              align="center"
              prop="createTime"
              :formatter="dateFormatter"
              width="180px"
            />
            <el-table-column label="操作" align="center" min-width="120px">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="viewReportDetail(scope.row)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            :total="receivedTotal"
            v-model:page="receivedQueryParams.pageNo"
            v-model:limit="receivedQueryParams.pageSize"
            @pagination="getReceivedList"
          />
        </div>
      </el-tab-pane>
    </el-tabs>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <WorkReportForm ref="formRef" @success="getSentList" />

  <!-- 汇报详情弹窗 -->
  <el-dialog
    v-model="detailDialogVisible"
    title="汇报详情"
    width="60%"
    :close-on-click-modal="false"
  >
    <div v-if="currentReportDetail">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="汇报类型">
          <dict-tag :type="DICT_TYPE.OA_REPORT_STATUS" :value="currentReportDetail.reportType" />
        </el-descriptions-item>
        <el-descriptions-item label="汇报人">
          <user-label :user-id="currentReportDetail.creator" />
        </el-descriptions-item>
        <el-descriptions-item label="汇报周期">
          {{ currentReportDetail.reportPeriod }}
        </el-descriptions-item>
        <el-descriptions-item label="汇报时间">
          {{ dateFormatter('', '', currentReportDetail.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="本期工作内容" :span="2">
          <div class="whitespace-pre-wrap">{{ currentReportDetail.currentWork }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="下期计划" :span="2">
          <div class="whitespace-pre-wrap">{{ currentReportDetail.nextPlan }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="其它事项" :span="2">
          <div class="whitespace-pre-wrap">{{ currentReportDetail.otherMatters }}</div>
        </el-descriptions-item>
        <el-descriptions-item :rowspan="3" label="附件">
          <OaFileManager :header="false"  :initial-file-ids="currentReportDetail.files" />
        </el-descriptions-item>

      </el-descriptions>
    </div>
    <template #footer>
      <el-button @click="detailDialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {  DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import { WorkReportApi, WorkReportVO } from '@/api/oa/workreport'
import WorkReportForm from './WorkReportForm.vue'
import UserLabel from '@/views/system/user/UserLabel.vue'
import UserSelect from '@/views/system/user/UserSelect.vue'

/** 工作汇报 列表 */
defineOptions({ name: 'WorkReport' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// Tab 相关
const activeTab = ref('sent')

const handleUserSelect = (val) =>{
  queryParams.userId = val ? val.id : undefined
  console.log('queryParams.userId',queryParams.userId)
}

// 发送的汇报相关
const sentLoading = ref(true) // 列表的加载中
const sentList = ref<WorkReportVO[]>([]) // 列表的数据
const sentTotal = ref(0) // 列表的总页数
const sentQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  reportType: undefined,
  creator: undefined,
  recipient: undefined,
  reportDate: [],
  createTime: []
})
const sentQueryFormRef = ref() // 搜索的表单

// 接收的汇报相关
const receivedLoading = ref(true) // 列表的加载中
const receivedList = ref<WorkReportVO[]>([]) // 列表的数据
const receivedTotal = ref(0) // 列表的总页数
const receivedQueryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  reportType: undefined,
  reporter: undefined, // 汇报人
  reportDate: [],
  createTime: []
})
const receivedQueryFormRef = ref() // 搜索的表单

// 详情弹窗相关
const detailDialogVisible = ref(false)
const currentReportDetail = ref<WorkReportVO | null>(null)


/** Tab 切换处理 */
const handleTabChange = (tabName: string) => {
  if (tabName === 'sent') {
    getSentList()
  } else if (tabName === 'received') {
    getReceivedList()
  }
}

/** 查询发送的汇报列表 */
const getSentList = async () => {
  sentLoading.value = true
  try {
    const data = await WorkReportApi.getWorkReportPage(sentQueryParams)
    sentList.value = data.list
    sentTotal.value = data.total
  } finally {
    sentLoading.value = false
  }
}

// /** 查询接收的汇报列表 */ todo
const getReceivedList = async () => {
  receivedLoading.value = true
  try {
    // 这里需要调用接收汇报的API，假设有单独的接口
    const data = await WorkReportApi.getReportPage(receivedQueryParams)
    receivedList.value = data.list
    receivedTotal.value = data.total
  } finally {
    receivedLoading.value = false
  }
}

/** 发送汇报搜索按钮操作 */
const handleSentQuery = () => {
  sentQueryParams.pageNo = 1
  getSentList()
}

/** 发送汇报重置按钮操作 */
const resetSentQuery = () => {
  sentQueryFormRef.value.resetFields()
  handleSentQuery()
}

/** 接收汇报搜索按钮操作 */
const handleReceivedQuery = () => {
  receivedQueryParams.pageNo = 1
  getReceivedList()
}

/** 接收汇报重置按钮操作 */
const resetReceivedQuery = () => {
  receivedQueryFormRef.value.resetFields()
  handleReceivedQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 发送汇报删除按钮操作 */
const handleSentDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await WorkReportApi.deleteWorkReport(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getSentList()
  } catch {}
}


/** 查看汇报详情 */
const viewReportDetail = (report: WorkReportVO) => {
  currentReportDetail.value = report
  detailDialogVisible.value = true
}

/** 查看附件 */
const viewAttachments = (attachmentUrls: string) => {
  // 这里可以实现附件查看逻辑，比如在新窗口打开
  if (attachmentUrls) {
    const urls = attachmentUrls.split(',').map(url => url.trim())
    urls.forEach(url => {
      if (url) {
        window.open(url, '_blank')
      }
    })
  }
}

/** 初始化 **/
onMounted(() => {
  getSentList()
  getReceivedList()
})
</script>

<style scoped>
.whitespace-pre-wrap {
  white-space: pre-wrap;
  word-break: break-word;
}
</style>
